<template>
    <div class="content-box" :style="'min-height:' + clientHeight + 'px;'">
      <!-- 顶部标签内容 -->
      <div class="top-content-box">
        <div class="left-content-box column">
          <div class="row" style="display:flex;align-items:center;">
            账户总余额(元)<van-icon
              size="20"
              :class="
                !hidden ? 'iconfont ic_eye_line' : 'iconfont ic_eye_close_line'
              "
              @click="toHidden"
            ></van-icon>
          </div>
          <div class="money-flex-box">
            <!-- {{ hidden ? '******' : studentInfo.money }} -->
            {{ studentInfo.user_name }}
          </div>
          <div class="van-ellipsis" style="margin-top:20px;">
            单位：{{ loginForm.top_organ
            }}<span v-show="loginForm.agency_name != ''"
              >（{{ loginForm.agency_name }}）</span
            >
          </div>
        </div>
        <div class="right-content-box column">
          <div class="name-flex-box">
            {{ hidden ? '******' : studentInfo.user_money }}
          </div>
          <div class="row record-content-box van-ellipsis" @click="toRecord">
            消费记录<van-icon name="arrow" />
          </div>
        </div>
      </div>
      <!-- 充值金额 -->
      <!-- <div class="total-num-box">充值金额</div> -->
      <div style="padding:0 15px;">
        <Title title="充值金额"></Title>
      </div>
      <van-row gutter="20" style="padding:0 4%;margin-top:10px;">
        <van-col span="8" v-for="(item, index) in moneyList" :key="index">
          <div
            class="common-money-box"
            :class="idx == index ? 'is_active-box' : ''"
            @click="choiceIndex(index)"
          >
            {{ item }}元
          </div>
        </van-col>
      </van-row>
      <!-- 充值其他金额 -->
      <div style="padding:0 15px;font-family: Bold;font-size: 17px;">
        <!-- <Title title="充值其它金额"></Title> -->
        充值其它金额
      </div>
      <div class="input-number-box">
        <van-field
          v-model="number"
          @input="valueInput"
          type="number"
          placeholder="请输入充值金额（元）"
        />
      </div>
      <!-- 备注 -->
      <!-- <div style="padding:0 15px;margin-top:20px;font-family: Bold;font-size: 17px;">
        备注
      </div>
      <div class="input-number-box">
        <van-field
          v-model="remark"
          maxlength="4"
          type="text"
          placeholder="请输入备注（选填）"
        /> -->
      <!-- </div> -->
      <!-- btn -->
      <van-row :gutter="20" class="btn-row-box" style="padding:30px 15%;margin-top:15px;">
        <van-col :span="24">
          <van-button :disabled="idx == 100 && number == ''" round block size="large" color="#146AF7" @click="toSave"
            >充 值</van-button
          >
        </van-col>
      </van-row>
      <!-- 充值提示弹框 -->
      <van-overlay :show="show" teleport="#app">
        <div class="wrapper">
          <div class="block column">
            <div class="row">
              确定充值金额<span style="color:#F04D53;margin-left:10px;"
                >{{ money }}元</span
              >？
            </div>
            <van-row :gutter="20" class="row-btn-model">
              <van-col :span="12"  @click="sumbit">取 消</van-col>
              <van-col :span="12" class="save-btn-box" @click="show = false"
                >确 定</van-col
              >
            </van-row>
          </div>
        </div>
      </van-overlay>
    </div>
  </template>
  <script lang="ts" setup>
  import { Toast } from 'vant'
  import { ref, reactive, onMounted, nextTick, onUnmounted } from 'vue'
  import { apiPay, Pay, adddb, postPay } from '../components/Options/SchoolQues'
  // import wx from 'weixin-js-sdk-ts'
  import { useStore } from 'vuex'
  import { useRouter } from 'vue-router'
  const store = useStore()
  const router = useRouter()
  const hidden = ref(false)
  const loginForm = ref<any>(store.state.loginForm)
  const studentInfo = ref({
    user_name: '',
    user_money: ''
  })
  const pay = ref<boolean>(true)
  const show = ref(false)
  const money = ref<any>('0')
  const moneyList = ref([100, 200, 300, 500, 600, 1000])
  const clientHeight = window.innerHeight - 97
  // 选中的金额
  const idx = ref<any>(100)
  const remark = ref('')
  const number = ref<any>('')
  // 点击眼睛，展示或隐藏金额
  const toHidden = () => {
    hidden.value = !hidden.value
  }
  // 点击充值记录
  const toRecord = () => {
    router.push('/record')
  }
  // 点击充值金额选中
  const choiceIndex = (val: number) => {
    if (idx.value !== val) {
      idx.value = val
      number.value = ''
    } else {
      idx.value = 100
    }
  }
  // 自定义充值金额有变化时
  const valueInput = () => {
    idx.value = 100
    if (Number(number.value) > 9999) {
      Toast('您最多可充值9999元')
      number.value = 9999
    }
  }
  // 点击充值
  const toSave = () => {
    if (number.value !== '') {
      if(Number(number.value) === 0){
        return Toast('请输入正确金额')
      }
      money.value = number.value
    } else {
      money.value = moneyList.value[idx.value]
    }
    show.value = true
  }
  // 弹框中的确定，为真实调取充值支付接口
  const sumbit = async () => {
    if (pay.value) {
      pay.value = false
      const params: adddb = {
        adddb: {
          mode: 'wechatRecharge',
          money: money.value
        }
      }
      const res: any = await postPay(params)
      if (res.code !== 1) {
        return Toast(res.msg)
      }
      // console.log(res.data)
      window.sessionStorage.setItem('money', money.value)
      // console.log(res.data)
      weixinPay(res.data)
      setTimeout(() => {
        pay.value = true
      }, 5000)
    }
  }
  // 网页加载即获取个人信息
  const getUser = async () => {
    const params: Pay = {
      mode: 'getMoney'
    }
    const res: any = await apiPay(params)
    if (res.code !== 1) {
      return Toast(res.msg)
    }
    studentInfo.value = res.data
  }
  // 微信内置的支付接口
  const weixinPay = (data: any) => {
    if (typeof WeixinJSBridge === 'undefined') {
      // 微信浏览器内置对象。参考微信官方文档
      // if (document.addEventListener) {
      //   document.addEventListener(
      //     'WeixinJSBridgeReady',
      //     onBridgeReady(data),
      //     false
      //   )
      // } else if (document.attachEvent) {
      //   document.attachEvent('WeixinJSBridgeReady', onBridgeReady(data))
      //   document.attachEvent('onWeixinJSBridgeReady', onBridgeReady(data))
      // }
    } else {
      onBridgeReady(data)
    }
  }
  const onBridgeReady = (data: any) => {
    // var vm = this
    WeixinJSBridge.invoke(
      'getBrandWCPayRequest',
      {
        appId: data.appId, // 公众号名称，由商户传入
        timeStamp: data.timeStamp, // 时间戳，自1970年以来的秒数
        nonceStr: data.nonceStr, // 随机串
        package: data.package,
        signType: data.signType, // 微信签名方式：
        paySign: data.paySign // 微信签名
        // 这里的信息从后台返回的接口获得。
        // jsApiList: ['chooseWXPay']
      },
      function (res: any) {
        // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
        if (res.err_msg === 'get_brand_wcpay_request:ok') {
          window.sessionStorage.setItem('bool', true as any)
          window.sessionStorage.setItem('time', data.timeStamp)
          window.sessionStorage.setItem('order', data.order_number)
          window.location.href = 'index.html#/result'
        } else {
          Toast.fail('取消支付！')
        }
      }
    )
  }
  // 网页加载即运行的代码
  onMounted(() => {
    if (loginForm.value.id) {
    } else {
      if (window.sessionStorage.getItem('loginForm')) {
        loginForm.value = JSON.parse(
          window.sessionStorage.getItem('loginForm') as any
        )
      }
    }
    // 网页加载即获取个人信息
    getUser()
  })
  </script>
  <style lang="scss" scoped>
  .content-box {
    width: 100%;
    height: auto;
    position: relative;
    box-sizing: border-box;
    background: #fff;
    .top-content-box {
      height: 180px;
      background-image: url('../assets/images/book_bg@2x.png');
      background-size: 100% 100%;
      display: flex;
      justify-content: space-between;
      .left-content-box {
        color: #fff;
        padding-top: 30px;
        padding-left: 10%;
        font-family: 'Medium';
        font-size: 14px;
        .van-icon {
          margin-left: 15px;
        }
        .money-flex-box {
          margin-top: 20px;
          font-size: 24px;
          font-family: 'Bold';
        }
      }
      .right-content-box {
        color: #fff;
        padding-top: 30px;
        padding-right: 10%;
        font-family: 'Medium';
        text-align: right;
        font-size: 14px;
        .name-flex-box {
          font-family: 'Bold';
          font-size: 24px;
          margin-bottom: 10px;
          margin-top: -5px;
        }
        .record-content-box {
          margin-top: 52px;
          font-size: 16px;
          display: flex;
          align-items: center;
          justify-content: flex-end;
          .van-icon {
            margin-left: 5px;
          }
        }
      }
    }
    .common-money-box {
      background: #f4f6fa;
      color: #333333;
      padding: 12px 0;
      font-family: 'Medium';
      border-radius: 5px;
      text-align: center;
      margin-bottom: 20px;
    }
    .is_active-box {
      background: #146af7;
      color: #fff;
    }
    .input-number-box {
      border-bottom: 1px solid rgba(153, 153, 153, 0.2);
      width: 92%;
      margin-left: 4%;
    }
  }
  .wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }
  
  .block {
    width: 70%;
    height: auto;
    border-radius: 14px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 18px;
    padding-top: 34px;
    background-color: #fff;
    font-family: 'Bold';
    color: #333;
    .row-btn-model {
      margin-top: 34px;
      padding: 20px 0;
      text-align: center;
      width: 100%;
      color: #999999;
      .save-btn-box {
        color: #034afd;
        position: relative;
      }
      .save-btn-box::before {
        content: '';
        position: absolute;
        left: 0;
        width: 1px;
        height: 25px;
        background: #bcbcbc;
      }
    }
  }
  </style>
  